import random
import time
from alipay import AliPay
from rest_framework.views import APIView
from rest_framework.response import Response
from order.models import TasteGood, Order, GoodOreder
from order.serializer import TasteGoodSerializer, OrderSerializer, GoodOrederSerializer
from take_out_food import settings
from user.views import check_user

# 口味菜品
class TastGoodInfo(APIView):
    @check_user
    def get(self,request,payload):
        user_id = payload['id']
        taste = TasteGood.objects.all()
        ser = TasteGoodSerializer(taste,many=True)
        return Response({
            'code':200,'msg':ser.data
        })

    @check_user
    def post(self,request,payload):
        user_id = payload['id']
        some_taster = request.data.get('some_taster')
        user_id = request.data.get('user_id')
        good_id = request.data.get('good_id')
        TasteGood.objects.create(some_taster=some_taster,user_id_id=user_id,good_id_id=good_id)
        return Response({
            'code':200,'msg':'添加成功'
        })

# 订单
class OrderInfoView(APIView):
    @check_user
    def get(self,request,payload):
        user_id = payload['id']
        order = Order.objects.all()
        ser = OrderSerializer(order,many=True)
        return Response({
            'code':200,'msg':'获取成功',
            'order':ser.data
        })

    @check_user
    def post(self,request,payload):
        user_id = payload['id']
        status = request.data.get('status')
        money = request.data.get('money')
        info = request.data.get('info')
        type = request.data.get('type')
        user = request.data.get('user')
        address = request.data.get('address')


        Order.objects.create(status=status,money=money,info=info,
                    type=type,user_id=user,address_id=address)

        return Response({
            'code':200,'msg':'添加成功'
        })




# 商品订单 -->店家查询
class GoodOrderInfo(APIView):
    @check_user
    def get(self,request,payload):
        user_id = payload['id']
        good_order = GoodOreder.objects.filter(id=user_id).all()
        ser = GoodOrederSerializer(good_order,many=True)
        return Response({
            'code':200,'msg':ser.data
        })

    @check_user
    def post(self,request,payload):
        user_id = payload['id']
        num = request.data.get('num')
        price = request.data.get('price')
        comment = request.data.get('comment')
        score = request.data.get('score')
        is_anonymous = request.data.get('is_anonymous')
        is_commented = request.data.get('is_commented')
        order = request.data.get('order')
        goods = request.data.get('goods')
        GoodOreder.objects.create(num=num,price=price,comment=comment,score=score,
            is_anonymous=is_anonymous,is_commented=is_commented,order_id=order,goods_id=goods)
        return Response({
            'code':200,'msg':'添加订单成功'
        })

class GoodOrderInfoView(APIView):
    @check_user
    def get(self,request,payload,pk):
        user_id = payload['id']
        goodorder = GoodOreder.objects.filter(id=pk).first()
        ser = GoodOrederSerializer(goodorder)
        return ser.data

    @check_user
    def delete(self,request,payload,pk):
        user_id = payload['id']
        GoodOreder.objects.filter(id=pk).delete()
        return Response({
            'code':200,'msg':'删除订单成功'
        })



# 支付
class AliPayOrder(APIView):
    @staticmethod
    def ali_pay():
        alipay = AliPay(
            appid='2021000119664047',  # 你的支付宝沙箱应用的id
            app_private_key_string=open(settings.APP_PRIVATE_KEY_PATH).read(),  # 你的私钥
            alipay_public_key_string=open(settings.ALIPAY_PUBLIC_KEY_PATH).read(),  # 支付宝公钥
            app_notify_url=None,  # 回调地址
            sign_type='RSA2',  # 签名算法
            debug=True,  # 请求来到支付宝沙箱
        )
        return alipay

    def post(self, request):  # 生成支付地址的方法

        order_id = request.data.get("order_id")  # 订单编号
        total_price = request.data.get("total_price")  # 价格
        print(order_id, total_price)
        order_string = self.ali_pay().api_alipay_trade_page_pay(
            subject='商家收款',
            out_trade_no=order_id,  # 订单号
            total_amount=total_price,
            return_url='http://localhost:8080/pay_callback',  # 支付后跳转的地址
            notify_url=None  # 异步通知地址
        )
        return Response(
            {'message': "正在跳转支付页面", 'code': '200', 'data': 'https://openapi.alipaydev.com/gateway.do?' + order_string})


# 处理支付后的回调  看是否支付成功了
class PayCallbackCheck(APIView):
    def post(self, request):
        data = request.data  # data 获取前端传来的所有数控v
        # print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', data)
        signature = data.pop('sign')
        out_trade_no = data['out_trade_no']
        # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>signature", signature, out_trade_no)
        success = AliPayOrder().ali_pay().verify(data, signature)

        # # 根据订单查询支付结果
        res = AliPayOrder().ali_pay().api_alipay_trade_query(out_trade_no)  # <class 'dict'>
        # print("支付结果", res)
        send_pay_date = res['send_pay_date']  # 支付时间
        # total_amount = res['total_amount']  # 支付金额
        # print("订单支付结果>>>>>>>>>", res, type(res), res['code'])
        # """{'code': '10000', 'msg': 'Success', 'trade_status': 'TRADE_SUCCESS'}"""
        if success and res["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
            # 该状态是支付成功
            # 修改订单状态
            try:
                order = Order.objects.filter(order_id=out_trade_no).first()
                # 修改订单状态 为代发货
                order.status = 1
                order.pay_time = send_pay_date
                order.save()
                return Response({'code': 200, 'message': "支付成功"})
            except Exception as e:
                # print('修改订单状态保错: %s' % e)
                return Response({"code": 500, 'message': "服务器错误"})
        return Response({'code': 400, 'message': "支付失败"})

